package edu.chinasoft.servlet;

import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.annotation.WebServlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import edu.chinasoft.pojo.Goods;
import edu.chinasoft.service.GoodsService;
import edu.chinasoft.service.GoodsServiceImp;

/**
 * 
 * @author cjogng
 * @date 2020年1月16日:下午4:10:07
 * @version V1.0
 * @Description: 添加商品到数据库里
 */
@WebServlet(name = "myAddGoodsForServlet02", value = "/servlet/addgoodsforservlet02")
public class AddGoodsForServlet02 extends HttpServlet {
	private static Logger logger = Logger.getLogger(AddGoodsForServlet02.class);
	private GoodsService goodsService = new GoodsServiceImp();

	/**
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		logger.debug(" AddGoodsForServlet02 >doGet start.......");

		logger.debug(" AddGoodsForServlet02 >doGet end.......");
	}

	/**
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug(" AddGoodsForServlet02 >doPost start.......");
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();

		// 创建ServletFileUpload类对象
		DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
		ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

		// 获取表单里的所有标签对象 FileItem 表示表单里的标签 (如果想获取，表单标签必须要设置name属性)

	

		// 2：把值封装到goods对象里
		Goods goods = new Goods();
		try {
			List<FileItem> fileItemList = servletFileUpload.parseRequest(request);

			for (FileItem element : fileItemList) {
				if (element.isFormField()) { // 表示普通标签
					String key = element.getFieldName();
					String value = element.getString("utf-8");

					if (key.equals("goods_name")) {
						goods.setGoodsName(value);
					} else if (key.equals("goods_desc")) {
						goods.setGoodsDesc(value);
					} else if (key.equals("goods_price")) {
						goods.setGoodsPrice(Double.parseDouble(value));
					} else {
						goods.setGoodsStock(Integer.parseInt(value));
					}

				} else { // 表示文件上传标签
					// ServletContext servletContext = this.getServletContext();
					// String fileUploadPath = servletContext
					// .getRealPath("/upload/" + fileUploadName + "");
					//获取所要上传文件的名字
					String fileContext = element.getName();
					String fileUploadName = fileContext.substring(fileContext.lastIndexOf("\\")+1);
				    logger.debug(fileUploadName);

					String fileUploadPath = request.getRealPath("/upload/" + fileUploadName + "");

					File fileUploadFile = new File(fileUploadPath);
					element.write(fileUploadFile); // 把所选中的文件上传到相应的目录里
					
					
					goods.setGoodsImage("/upload/" + fileUploadName + "");
					
					
				}

			}

			// 3：调用服务器层方法把商品保存到数据库里
			boolean flag = goodsService.addGoods(goods);

			// 4：成功之后跳转到成功页面，失败之后跳转到添加商品页面

			if (flag) {
				response.sendRedirect("/project01/servlet/findgoodspageforservlet");
			} else {
				response.sendRedirect("/project01/addgoodserror.html");
			}

		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		logger.debug(" AddGoodsForServlet02 >doPost end.......");
	}

}